package base.sound
{
	import flash.utils.Dictionary;
	
	public class SoundFactory
	{
		private var _soundList:Dictionary=new Dictionary(true);
		
		public function SoundFactory()
		{
			
		}
		
		private static var _instance:SoundFactory;	
		public static function get Instance():SoundFactory
		{
			if(_instance == null)
			{
				_instance = new SoundFactory();
			}
			return _instance;
		}
		
		public function createSound(className:String, loop:int=0, volumn:int=100):SoundBase
		{
			var soundBase:SoundBase=new SoundBase(className, loop, volumn);
			_soundList[className]=soundBase;
			return soundBase;
		}
		
		public function clearSound(className:String):void
		{
			var soundBase:SoundBase=_soundList[className] as SoundBase;
			delete _soundList[className];
			if(soundBase)
			{
				soundBase.removeEventListener(SoundEvent.PLAY_END, __onSoundPlayEnd);
				soundBase.dispose();
			}
			soundBase=null;
		}
		
		public function deleteSound(className:String):void
		{
			delete _soundList[className];
		}		
		
		/**
		 *设置所有声音的大小
		 * @param soundVolumn 声音的大小值(1-100) 
		 * 
		 */		
		public function setAllVolumn(volumn:int):void
		{
			for each(var soundBase:SoundBase in _soundList)
			{
				soundBase.volumn=volumn;
			}
		}
		
		/**
		 *设置所有声音的大小
		 * @param soundVolumn 声音的大小值(1-100) 
		 * 
		 */		
		public function stopAllSound():void
		{
			for each(var soundBase:SoundBase in _soundList)
			{
				soundBase.stop();
			}
		}
		
		/**
		 *创建并播放声音 
		 * @param className 声音类名
		 * @param loop 循环次数,-1为无限循环
		 * @param volumn 音量大小
		 * 
		 */		
		public function createAndPlay(className:String, loop:int=0, volumn:int=100):SoundBase
		{
			var soundBase:SoundBase=createSound(className, loop, volumn);
			soundBase.addEventListener(SoundEvent.PLAY_END, __onSoundPlayEnd);
			soundBase.play();
			return soundBase;
		}
		
		private function __onSoundPlayEnd(evt:SoundEvent):void
		{
			var soundBase:SoundBase=evt.target as SoundBase;
			soundBase.removeEventListener(SoundEvent.PLAY_END, __onSoundPlayEnd);
			soundBase.dispose();
			soundBase=null;
		}
	}
}